package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)

type user struct {
	uid      int
	username string
	created  string
}

func main() {
	db, err := sql.Open("mysql", "root:ilovec@tcp(127.0.0.1:3306)/sbb")
	checkErr(err)
	defer db.Close()

	// insert
	stmt, err := db.Prepare("insert user(username, created) values( ?, ?)")
	checkErr(err)

	res, err := stmt.Exec("sbb2", "2017-12-27")
	checkErr(err)

	id, err := res.LastInsertId()
	checkErr(err)

	// update
	stmt, err = db.Prepare("update user set username = ? where uid = ?")
	checkErr(err)

	res, err = stmt.Exec("sbb1", id)
	checkErr(err)

	fmt.Println(res.RowsAffected())
	checkErr(err)

	// select
	rows, err := db.Query("select * from user")
	checkErr(err)

	for rows.Next() {
		var u user
		err = rows.Scan(&u.uid, &u.username, &u.created)
		checkErr(err)
		fmt.Println(u.uid)
		fmt.Println(u.username)
		fmt.Println(u.created)
	}

	fmt.Println(id)

}

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}
